<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <!-- Logo区域 -->
      <a-col flex="200px" class="logo-col">
        <router-link to="/" class="logo-container">
          <div class="title-bar">
            <img class="logo" src="../assets/logo.png" alt="花海图库logo" />
            <div class="title">花海图库</div>
          </div>
        </router-link>
      </a-col>

      <!-- 导航菜单 -->
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          class="custom-menu"
          @click="doChangeMenu"
        />
      </a-col>

      <!-- 用户信息展示页面 -->
      <a-col flex="auto" class="user-info">
        <div class="login-wrapper">
          <div v-if="LoginUserStore.loginUser.id">
            <a-dropdown arrow>
              <a-avatar class="user-avatar" :size="32" :src="LoginUserStore.loginUser.userAvatar" />
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="doToUserInfo">
                    <UserOutlined style="margin-right: 8px" />
                    个人中心
                  </a-menu-item>
                  <a-menu-item >
                    <UserOutlined style="margin-right: 8px" />
                    我的空间
                    <router-link to="/space/check"></router-link>
                  </a-menu-item>
                  <a-menu-item @click="doLogout">
                    <LogoutOutlined style="margin-right: 8px" />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
            {{ LoginUserStore.loginUser.userName ?? '空白' }}
          </div>

          <div v-else>
            <a-button type="primary" shape="round" class="login-btn" href="/user/login"
            >登录
            </a-button>
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- 点击加号按钮弹出的对话框   -->
    <a-modal
      :open="showModalVisible"
      :closable="true"
      :mask-closable="true"
      :footer="null"
      @cancel="handleCancel"
      class="custom-modal"
    >
      <!-- 统一的可点击区域容器 -->
      <div class="upload-area" @click="goToPictureAddPage" >
        <!-- 图标 -->
        <span class="icon">
            <PictureOutlined style="font-size: 20px; margin-right: 20px; color: #4caf50" />
          </span>
        <!-- 文字区域 -->
        <div class="text">
          <h3 style="margin-bottom: 20px">上传到公共图库</h3>
          <p>您的图片将在审核通过后展示给所有用户</p>
        </div>
      </div>
      <div style="text-align: center; margin-top: 16px">
        <a-button type="default" @click="handleCancel" >取消</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { h, ref, computed, onMounted } from 'vue'
//@ts-ignore
import { MenuProps, message } from 'ant-design-vue'
import {
  HomeOutlined,
  LogoutOutlined,
  PlusOutlined,
  UserOutlined,
  PictureOutlined,
} from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/userLogin'
import { userLogoutUsingPost } from '@/api/userController'

const router = useRouter()
const LoginUserStore = useLoginUserStore()

// 定义原始数据源，防止被污染
const originalItems = [
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '主页',
    title: '主页',
  },
  {
    key: '/picture/add',
    // 将图标修改为按钮样式
    icon: () => h(PlusOutlined),
    title: '上传图片',
  },
  {
    key: '/barrage/show',
    label: '留言墙',
    title: '留言墙',
  },
  {
    key: '/admin/userManage',
    label: '管理',
    title: '用户管理',
    // 子菜单（下拉项）
    children: [
      {
        key: '/admin/userManage', // 子项1的路由
        label: '用户管理',
      },
      {
        key: '/admin/pictureManage', // 子项2的路由
        label: '图片管理',
      },
      {
        key: '/admin/spaceManage', // 子项3的路由
        label: '空间管理',
      },
      {
        key: '/admin/barrageManage', // 子项4的路由
        label: '弹幕管理',
      },
      {
        key: '/admin/commentManage', // 子项4的路由
        label: '评论管理',
      },
    ],
  },
  {
    key: '/author',
    label: '作者',
    title: '作者',
    onClick: () => window.open('https://gitee.com/hy040911/huahai-picture-frontend', '_blank'),
  },
]

// 添加一个自定义的菜单项，对以/admin开头的路由进行过滤
const filteredMenus = (menu = [] as MenuProps['items']) => {
  return menu?.filter((menu) => {
    // 筛选以/admin开头的路由
    if (menu?.key?.toString().startsWith('/admin')) {
      let loginUser = LoginUserStore.loginUser
      if (!loginUser || loginUser.userRole !== 'admin') {
        return false
      }
    }
    // 筛选以/picture开头的路由, 只有登录用户才能使用
    if (menu?.key?.toString().startsWith('/picture')) {
      let loginUser = LoginUserStore.loginUser
      if (!loginUser || (loginUser.userRole !== 'user' && loginUser.userRole !== 'admin')) {
        return false
      }
    }
    // 递归过滤子菜单（如果有子项）
    // 判断是否是子菜单类型，再递归处理 children
    //@ts-ignore
    if ('children' in menu && menu.children && menu.children.length > 0) {
      menu.children = filteredMenus(menu.children)
    }
    return true
  })
}

// 对原始数据源进行过滤，展示过滤后的菜单
const items = computed<MenuProps['items']>(() => filteredMenus(originalItems))

// 点击导航栏切换时触发
//@ts-ignore
const doChangeMenu = ({ key }) => {
  if (key === '/picture/add') {
    openDialog()
  } else {
    router.push({
      path: key,
    })
  }
}

// 当前页面高亮
const current = ref<string[]>(['/'])
// 监听高亮的变化，绑定当前页面点击的高亮
router.afterEach((to, from, next) => {
  current.value = [to.path]
})

// 退出登录
const doLogout = async () => {
  const res = await userLogoutUsingPost()
  if (res.data?.code === 0 && res.data.data) {
    // 移除全局登录态
    LoginUserStore.setLoginUser({})
    message.success('退出登录成功')
    await router.push({
      path: '/user/login',
    })
  } else {
    message.error('退出登录失败' + res.data?.message)
  }
}

// 跳转到用户信息页面
const doToUserInfo = async () => {
  await router.push({
    path: '/user/info',
  })
}

const showModalVisible = ref(false)

// 打开对话框的方法，供父组件调用
const openDialog = () => {
  showModalVisible.value = true
}

// 关闭对话框
const handleCancel = () => {
  showModalVisible.value = false
}

// 新增：跳转方法（点击上传区域时触发）
const goToPictureAddPage = () => {
  showModalVisible.value = false
  // 解析路由为URL
  const uploadUrl = router.push({
    path: '/picture/add',
  })

}

</script>

<style scoped>
#globalHeader {
  background-color: #fff;
}

.title-bar {
  display: flex;
  align-items: center;
}

.logo-container {
  display: flex;
  align-items: center;
  height: 100%;
}

.logo {
  height: 54px;
  width: 54px;
  object-fit: contain;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.title {
  color: #333;
  font-size: 20px;
  font-weight: 600;
  margin-left: 12px;
  white-space: nowrap; /* 防止标题被换行 */
}

.custom-menu {
  border-bottom: none;
  height: 100%;

  .ant-menu-item {
    height: 100%;
    display: flex;
    align-items: center;
    margin-right: 8px;
    border-radius: 20px;
    padding: 0 12px; /* 减小菜单项内边距 */

    &:hover {
      background-color: rgba(76, 175, 80, 0.1);
    }

    &.ant-menu-item-selected {
      background-color: rgba(76, 175, 80, 0.2);
      color: #2e7d32;
    }
  }
}

.user-info {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 24px;
}

.user-avatar {
  margin-right: 12px;
}

.login-wrapper {
  margin-right: 24px; /* 将右侧内边距改为外边距 */
  display: flex;
  align-items: center;
  gap: 12px;
}

.login-btn {
  height: 36px;
  background-color: #4caf50;
  border-color: #4caf50;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.2);
  transition: all 0.3s ease;
}

/* 对话框样式调整 */
/* 1. 对话框透明度（穿透到a-modal的内容容器） */
:deep(.custom-modal .ant-modal-content) {
  opacity: 0.9; /* 透明度（0.9适中，0.8-0.95区间可调整） */
  border-radius: 8px; /* 增加圆角让样式更和谐 */
  min-height: 400px; /* 确保对话框有足够高度 */
}

/* 2. 跳转区域（upload-area）的灰度效果 */
.upload-area {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  margin-top: 26px;
  cursor: pointer;
  transition: all 0.3s ease;
  filter: grayscale(80%); /* 默认灰度80%（比之前稍浅，避免太暗） */
}

.upload-area:hover {
  filter: grayscale(0%); /* 鼠标悬浮时完全去灰度 */
  background-color: rgba(76, 175, 80, 0.05); /* 增加悬浮背景色增强交互感 */
}

.upload-area .icon {
  margin-right: 12px;
}

.upload-area .text {
  display: flex;
  flex-direction: column;
}

.upload-area .text h3 {
  font-size: 16px;
  font-weight: bold;
  color: #ff9800;
  margin: 0 0 8px 0;
}

.upload-area .text p {
  color: #666;
  margin: 0;
}

/* 取消按钮样式调整 */
.ant-modal-footer {
  display: none;
}

.ant-modal-body {
  padding: 16px;
}
</style>
